<?php

namespace Magein\LaravelUtils;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use Magein\PhpUtils\Result;

class ApiResponse
{

    /**
     * @param $message
     * @param $code
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public static function error($message, $code = 1, $data = null)
    {
        return self::result(Result::error($message, $code, $data));
    }

    /**
     * @param $data
     * @param $message
     * @param $code
     * @return \Illuminate\Http\JsonResponse
     */
    public static function success($data = null, $message = '', $code = 0)
    {
        return self::result(Result::success($data, $message, $code));
    }

    public static function result($result)
    {
        if ($result instanceof Result) {
            return response()->json($result->toArray());
        }

        if ($result instanceof LengthAwarePaginator) {
            $data = [
                'pages' => [
                    'current_page' => $result->currentPage(),
                    'per_page' => $result->perPage(),
                    'total' => $result->total(),
                    'last_page' => $result->lastPage(),
                    'has_more' => $result->hasMorePages(),
                    //获取结果集中第一个数据的编号
                    'from' => $result->firstItem(),
                    // 获取结果集中最后一个数据的编号
                    'to' => $result->lastItem(),
                ],
                'items' => $result->items(),
            ];
        } elseif ($result instanceof Collection) {
            $data = $result->toArray();
        } else {
            $data = $result;
        }

        return response()->json(Result::success($data)->toArray());
    }
}
